<template>
  <div class="order-filter">
    <!-- 高级筛选面板 -->
    <div class="filter-panel" :class="{ 'filter-panel--expanded': expanded }">
      <div class="filter-panel__content">
        <!-- 日期范围选择器 -->
        <div class="filter-group">
          <div class="filter-group__label">订单日期</div>
          <div class="filter-group__content date-range">
            <input
              type="date"
              class="date-input"
              v-model="filters.dateRange.start"
              :max="filters.dateRange.end || today"
            />
            <span class="date-separator">至</span>
            <input
              type="date"
              class="date-input"
              v-model="filters.dateRange.end"
              :min="filters.dateRange.start"
              :max="today"
            />
          </div>
        </div>

        <!-- 价格区间滑块 -->
        <div class="filter-group">
          <div class="filter-group__label">订单金额 (¥{{ formatNumber(filters.priceRange[0]) }} - ¥{{ formatNumber(filters.priceRange[1]) }})</div>
          <div class="filter-group__content">
            <div class="range-slider">
              <div class="range-slider__track">
                <div 
                  class="range-slider__progress"
                  :style="{
                    left: ((filters.priceRange[0] - priceRange.min) / (priceRange.max - priceRange.min) * 100) + '%',
                    width: (((filters.priceRange[1] - filters.priceRange[0]) / (priceRange.max - priceRange.min)) * 100) + '%'
                  }"
                ></div>
              </div>
              <input
                type="range"
                class="range-input range-input--min"
                :min="priceRange.min"
                :max="priceRange.max"
                :step="priceRange.step"
                v-model.number="filters.priceRange[0]"
                @input="ensurePriceRangeOrder"
              />
              <input
                type="range"
                class="range-input range-input--max"
                :min="priceRange.min"
                :max="priceRange.max"
                :step="priceRange.step"
                v-model.number="filters.priceRange[1]"
                @input="ensurePriceRangeOrder"
              />
            </div>
            <div class="range-labels">
              <span>¥{{ formatNumber(priceRange.min) }}</span>
              <span>¥{{ formatNumber(priceRange.max) }}</span>
            </div>
          </div>
        </div>

        <!-- 佣金金额范围 -->
        <div class="filter-group">
          <div class="filter-group__label">佣金金额</div>
          <div class="filter-group__content commission-range">
            <div class="commission-input-group">
              <span class="input-prefix">¥</span>
              <input
                type="number"
                class="commission-input"
                placeholder="最小值"
                v-model.number="filters.commissionRange[0]"
                min="0"
                @input="validateCommissionRange"
              />
            </div>
            <span class="range-separator">至</span>
            <div class="commission-input-group">
              <span class="input-prefix">¥</span>
              <input
                type="number"
                class="commission-input"
                placeholder="最大值"
                v-model.number="filters.commissionRange[1]"
                min="0"
                @input="validateCommissionRange"
              />
            </div>
          </div>
        </div>

        <!-- 商品分类多选框 -->
        <div class="filter-group">
          <div class="filter-group__label">商品分类</div>
          <div class="filter-group__content category-checkboxes">
            <div 
              class="category-item" 
              v-for="category in categories" 
              :key="category.value"
              :class="{ 'category-item--selected': filters.categories.includes(category.value) }"
              @click="toggleCategory(category.value)"
            >
              <div class="checkbox">
                <i class="fas fa-check" v-if="filters.categories.includes(category.value)"></i>
              </div>
              <span class="category-label">{{ category.label }}</span>
            </div>
          </div>
        </div>

        <!-- 按钮区域 -->
        <div class="filter-buttons">
          <button class="btn-reset" @click="resetFilters">
            <i class="fas fa-undo"></i> 重置
          </button>
          <button class="btn-apply" @click="applyFilters">
            <i class="fas fa-check"></i> 应用筛选
          </button>
        </div>
      </div>
    </div>

    <!-- 已选筛选条件标签 -->
    <div class="filter-tags" v-if="hasActiveFilters">
      <div class="tags-label">已筛选:</div>
      <div class="tags-list">
        <div class="filter-tag" v-if="filters.dateRange.start || filters.dateRange.end">
          <span>日期: {{ formatDateRange(filters.dateRange) }}</span>
          <button class="tag-remove" @click="clearDateRange">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="filter-tag" v-if="isPriceRangeActive">
          <span>价格: ¥{{ formatNumber(filters.priceRange[0]) }} - ¥{{ formatNumber(filters.priceRange[1]) }}</span>
          <button class="tag-remove" @click="clearPriceRange">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="filter-tag" v-if="isCommissionRangeActive">
          <span>佣金: ¥{{ formatNumber(filters.commissionRange[0] || 0) }} - ¥{{ formatNumber(filters.commissionRange[1] || commissionRange.max) }}</span>
          <button class="tag-remove" @click="clearCommissionRange">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="filter-tag" v-if="filters.categories.length">
          <span>分类: {{ formatCategories() }}</span>
          <button class="tag-remove" @click="clearCategories">
            <i class="fas fa-times"></i>
          </button>
        </div>
      </div>
      <button class="clear-all-tags" @click="resetFilters">
        清除全部
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

// 定义组件的Props
interface Props {
  expanded: boolean
  defaultFilters?: {
    dateRange?: { start: string, end: string }
    priceRange?: [number, number]
    commissionRange?: [number | null, number | null]
    categories?: string[]
  }
}

// 定义事件
interface Emits {
  (e: 'update:expanded', expanded: boolean): void
  (e: 'filter', filters: any): void
  (e: 'reset'): void
}

const props = withDefaults(defineProps<Props>(), {
  expanded: false,
  defaultFilters: () => ({})
})

const emit = defineEmits<Emits>()

// 价格范围配置
const priceRange = {
  min: 0,
  max: 1000,
  step: 10
}

// 佣金范围配置
const commissionRange = {
  min: 0,
  max: 500
}

// 今天的日期（用于日期选择器的max属性）
const today = new Date().toISOString().split('T')[0]

// 商品分类列表
const categories = [
  { label: '汉堡', value: 'burger' },
  { label: '炸鸡', value: 'chicken' },
  { label: '披萨', value: 'pizza' },
  { label: '面食', value: 'noodle' },
  { label: '米饭', value: 'rice' },
  { label: '沙拉', value: 'salad' },
  { label: '甜点', value: 'dessert' },
  { label: '饮料', value: 'drink' }
]

// 筛选条件
const filters = ref({
  dateRange: {
    start: props.defaultFilters.dateRange?.start || '',
    end: props.defaultFilters.dateRange?.end || ''
  },
  priceRange: props.defaultFilters.priceRange || [priceRange.min, priceRange.max],
  commissionRange: props.defaultFilters.commissionRange || [null, null],
  categories: props.defaultFilters.categories || []
})

// 是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return (
    filters.value.dateRange.start || 
    filters.value.dateRange.end || 
    isPriceRangeActive.value || 
    isCommissionRangeActive.value || 
    filters.value.categories.length > 0
  )
})

// 价格范围是否已修改
const isPriceRangeActive = computed(() => {
  return (
    filters.value.priceRange[0] > priceRange.min || 
    filters.value.priceRange[1] < priceRange.max
  )
})

// 佣金范围是否已修改
const isCommissionRangeActive = computed(() => {
  return (
    (filters.value.commissionRange[0] !== null && filters.value.commissionRange[0] > 0) || 
    (filters.value.commissionRange[1] !== null && filters.value.commissionRange[1] < commissionRange.max)
  )
})

// 确保价格范围的顺序正确（最小值不大于最大值）
const ensurePriceRangeOrder = () => {
  if (filters.value.priceRange[0] > filters.value.priceRange[1]) {
    filters.value.priceRange[1] = filters.value.priceRange[0]
  }
}

// 验证佣金范围
const validateCommissionRange = () => {
  const [min, max] = filters.value.commissionRange
  
  // 如果最小值不为空且大于最大值，则将最大值设为最小值
  if (min !== null && max !== null && min > max) {
    filters.value.commissionRange[1] = min
  }
}

// 切换分类选择
const toggleCategory = (categoryValue: string) => {
  const index = filters.value.categories.indexOf(categoryValue)
  if (index === -1) {
    filters.value.categories.push(categoryValue)
  } else {
    filters.value.categories.splice(index, 1)
  }
}

// 清除日期范围
const clearDateRange = () => {
  filters.value.dateRange = { start: '', end: '' }
}

// 清除价格范围
const clearPriceRange = () => {
  filters.value.priceRange = [priceRange.min, priceRange.max]
}

// 清除佣金范围
const clearCommissionRange = () => {
  filters.value.commissionRange = [null, null]
}

// 清除分类选择
const clearCategories = () => {
  filters.value.categories = []
}

// 重置所有筛选条件
const resetFilters = () => {
  clearDateRange()
  clearPriceRange()
  clearCommissionRange()
  clearCategories()
  emit('reset')
}

// 应用筛选条件
const applyFilters = () => {
  emit('filter', {
    dateRange: filters.value.dateRange,
    priceRange: filters.value.priceRange,
    commissionRange: filters.value.commissionRange,
    categories: filters.value.categories
  })
  // 如果在移动设备上，应用后自动关闭筛选面板
  if (window.innerWidth < 768) {
    emit('update:expanded', false)
  }
}

// 格式化数字
const formatNumber = (num: number | null): string => {
  if (num === null) return '0'
  return num.toFixed(2)
}

// 格式化日期范围显示
const formatDateRange = (range: { start: string, end: string }) => {
  if (range.start && range.end) {
    return `${formatShortDate(range.start)} 至 ${formatShortDate(range.end)}`
  } else if (range.start) {
    return `${formatShortDate(range.start)} 起`
  } else if (range.end) {
    return `至 ${formatShortDate(range.end)}`
  }
  return ''
}

// 简化日期格式
const formatShortDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 格式化分类显示
const formatCategories = () => {
  if (filters.value.categories.length === 0) return ''
  
  if (filters.value.categories.length <= 2) {
    return filters.value.categories.map(cat => {
      const category = categories.find(c => c.value === cat)
      return category ? category.label : cat
    }).join('、')
  }
  
  const firstTwo = filters.value.categories.slice(0, 2).map(cat => {
    const category = categories.find(c => c.value === cat)
    return category ? category.label : cat
  }).join('、')
  
  return `${firstTwo} 等${filters.value.categories.length}项`
}

// 监听props变化
watch(() => props.expanded, (newValue) => {
  // 可以在这里添加展开/折叠动画相关的代码
})
</script>

<style scoped lang="scss">
.order-filter {
  margin-bottom: 24px;
}

.filter-panel {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.3s ease-in-out;
  
  &--expanded {
    max-height: 1200px;
  }
  
  &__content {
    padding: 20px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }
}

.filter-group {
  &__label {
    font-size: 14px;
    font-weight: 500;
    color: #2F3542;
    margin-bottom: 8px;
  }
  
  &__content {
    width: 100%;
  }
}

// 日期范围样式
.date-range {
  display: flex;
  align-items: center;
  
  .date-input {
    flex: 1;
    height: 36px;
    padding: 0 12px;
    border: 1px solid #DFE3E8;
    border-radius: 4px;
    color: #2F3542;
    background-color: #fff;
    font-size: 14px;
    
    &:focus {
      outline: none;
      border-color: #FF4757;
      box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
    }
    
    &::-webkit-calendar-picker-indicator {
      cursor: pointer;
    }
  }
  
  .date-separator {
    margin: 0 8px;
    color: #6C757D;
  }
}

// 价格滑块样式
.range-slider {
  position: relative;
  height: 40px;
  width: 100%;
  margin-bottom: 8px;
  
  &__track {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0;
    right: 0;
    height: 6px;
    background-color: #E9ECEF;
    border-radius: 3px;
  }
  
  &__progress {
    position: absolute;
    height: 100%;
    background-color: #FF4757;
    border-radius: 3px;
  }
  
  .range-input {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 100%;
    height: 0;
    -webkit-appearance: none;
    pointer-events: none;
    background: none;
    outline: none;
    z-index: 10;
    
    &::-webkit-slider-thumb {
      -webkit-appearance: none;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background-color: #fff;
      border: 2px solid #FF4757;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      cursor: pointer;
      pointer-events: auto;
      transition: box-shadow 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 8px rgba(255, 71, 87, 0.1);
      }
    }
    
    &::-moz-range-thumb {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background-color: #fff;
      border: 2px solid #FF4757;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      cursor: pointer;
      pointer-events: auto;
      transition: box-shadow 0.2s;
      
      &:hover {
        box-shadow: 0 0 0 8px rgba(255, 71, 87, 0.1);
      }
    }
  }
}

.range-labels {
  display: flex;
  justify-content: space-between;
  color: #6C757D;
  font-size: 12px;
}

// 佣金范围样式
.commission-range {
  display: flex;
  align-items: center;
  
  .commission-input-group {
    position: relative;
    flex: 1;
    
    .input-prefix {
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      color: #6C757D;
      font-size: 14px;
    }
    
    .commission-input {
      width: 100%;
      height: 36px;
      padding: 0 12px 0 24px; // 为前缀留出空间
      border: 1px solid #DFE3E8;
      border-radius: 4px;
      color: #2F3542;
      background-color: #fff;
      font-size: 14px;
      
      &:focus {
        outline: none;
        border-color: #FF4757;
        box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
      }
      
      &::-webkit-inner-spin-button, 
      &::-webkit-outer-spin-button { 
        -webkit-appearance: none; 
        margin: 0; 
      }
    }
  }
  
  .range-separator {
    margin: 0 8px;
    color: #6C757D;
  }
}

// 分类复选框样式
.category-checkboxes {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.category-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #F8F9FA;
  }
  
  &--selected {
    background-color: #FFF0F0;
    
    .checkbox {
      background-color: #FF4757;
      border-color: #FF4757;
      color: #fff;
    }
  }
  
  .checkbox {
    width: 18px;
    height: 18px;
    border-radius: 3px;
    border: 1px solid #CED4DA;
    background-color: #fff;
    margin-right: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    transition: all 0.2s;
  }
  
  .category-label {
    font-size: 14px;
    color: #2F3542;
  }
}

// 按钮区域样式
.filter-buttons {
  grid-column: 1 / -1;
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  gap: 12px;
  
  .btn-reset, .btn-apply {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    i {
      margin-right: 6px;
    }
  }
  
  .btn-reset {
    background-color: #F8F9FA;
    color: #6C757D;
    border: 1px solid #DFE3E8;
    
    &:hover {
      background-color: #E9ECEF;
    }
  }
  
  .btn-apply {
    background-color: #FF4757;
    color: #fff;
    border: none;
    
    &:hover {
      background-color: darken(#FF4757, 10%);
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(255, 71, 87, 0.3);
    }
  }
}

// 筛选标签样式
.filter-tags {
  display: flex;
  align-items: center;
  margin-top: 16px;
  
  .tags-label {
    font-size: 13px;
    color: #6C757D;
    margin-right: 8px;
  }
  
  .tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    flex: 1;
    
    .filter-tag {
      display: inline-flex;
      align-items: center;
      padding: 4px 10px;
      background-color: #F3F4F6;
      border-radius: 4px;
      font-size: 12px;
      color: #4B5563;
      
      .tag-remove {
        background: none;
        border: none;
        color: #9CA3AF;
        cursor: pointer;
        margin-left: 6px;
        padding: 0;
        font-size: 10px;
        
        &:hover {
          color: #6B7280;
        }
      }
    }
  }
  
  .clear-all-tags {
    background: none;
    border: none;
    padding: 4px 8px;
    font-size: 12px;
    color: #FF4757;
    cursor: pointer;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .filter-tags {
    flex-direction: column;
    align-items: flex-start;
    
    .tags-label {
      margin-bottom: 8px;
    }
    
    .tags-list {
      width: 100%;
      margin-bottom: 8px;
    }
    
    .clear-all-tags {
      align-self: flex-end;
    }
  }
}
</style> 